package com.lagou.edu.authority.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lagou.edu.authority.entity.Role;
import com.lagou.edu.authority.mapper.RoleMapper;
import com.lagou.edu.authority.param.RoleQueryParam;
import com.lagou.edu.authority.service.IRoleMenuService;
import com.lagou.edu.authority.service.IRoleResourceService;
import com.lagou.edu.authority.service.IRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * TODO
 *
 * @author lm
 * @since 2021/11/4 14:31
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    IRoleMenuService roleMenuService;
    @Autowired
    IRoleResourceService roleResourceService;

    @Override
    public Page<Role> getRolePages(RoleQueryParam roleQueryParam) {
        Page<Role> page = new Page<>(roleQueryParam.getCurrent(), roleQueryParam.getSize());
        return lambdaQuery()
                .eq(Objects.nonNull(roleQueryParam.getId()), Role::getId, roleQueryParam.getId())
                .like(StringUtils.isNotBlank(roleQueryParam.getName()), Role::getName, roleQueryParam.getName())
                .eq(StringUtils.isNotBlank(roleQueryParam.getCode()), Role::getName, roleQueryParam.getCode())
                .ge(Objects.nonNull(roleQueryParam.getStartCreateTime()), Role::getCreatedTime, roleQueryParam.getStartCreateTime())
                .le(Objects.nonNull(roleQueryParam.getEndCreateTime()), Role::getCreatedTime, roleQueryParam.getEndCreateTime())
                .orderByDesc(Role::getId)
                .page(page);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean deleteRoleByRoleId(Integer id) {
        //userRoleService.removeByRoleId(id);
        roleMenuService.removeByRoleId(id);
        roleResourceService.removeByRoleId(id);
        return this.removeById(id);
    }
}
